<template>
    <div class="container">
        <div class="title">{{ $t('stm.branchTransReportOrg.monthlyStatistics') }}</div>
        <large-transaction ref="largeTransaction" :type="type" :date="date" :maxValue="maxValue"  :reqOrgNo="reqOrgNo" />
        <dubious-transaction ref="dubiousTransaction" :type="type" :date="date" :maxValue="maxValue"   :reqOrgNo="reqOrgNo"/>
        <div class="title" style="margin-bottom: 10px;margin-top: 10px">{{ $t('stm.branchTransReportOrg.scenariosLog') }}</div>
        <monitor-ledger ref="monitorLedger" :type="type" :date="date"  :reqOrgNo="reqOrgNo" />
        <template v-if="type === 'edit'">
            <div class="title" style="margin-bottom: 10px;">{{ $t('stm.branchTransReportOrg.modReason') }}</div>
            <bfe-input v-model="remark" type="textarea" :rows="3" :maxlength="10000"
                :placeholder="$t('stm.common.pleaseInput')"></bfe-input>
        </template>
        <template v-if="type !== 'add' && operationList.length > 0">
            <div class="title" style="margin-bottom: 10px;">{{ $t('stm.branchTransReportOrg.operateLog') }}</div>
            <bfe-table :data="operationList" border style="width: 100%" :height="300">
                <bfe-table-column prop="usrRefno" :label="$t('stm.branchTransReportOrg.userNo')"></bfe-table-column>
                <bfe-table-column prop="usnm" :label="$t('stm.branchTransReportOrg.userName')"></bfe-table-column>
                <bfe-table-column prop="optDesc" :label="$t('stm.branchTransReportOrg.operateDesc')"></bfe-table-column>
                <bfe-table-column prop="optTime" :label="$t('stm.branchTransReportOrg.operateTime')"
                    width="180"></bfe-table-column>
            </bfe-table>
            <bfe-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="tablePage.pageNo" :page-size="tablePage.pageSize"
                layout="total, prev, pager, next, jumper" :total="tablePage.total" />
        </template>
        <div style="margin-top: 10px;">
            <bfe-button @click="goBack">{{$t('stm.common.return')}}</bfe-button>
            <bfe-button v-if="type !== 'view'" type="primary" @click="onAdd">{{$t('stm.common.submit')}}</bfe-button>
        </div>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import mixin from '@/views/business/stm/mixins'
import moment from 'moment';
import LargeTransaction from "./largeTransaction";
import DubiousTransaction from "./dubiousTransaction";
import MonitorLedger from "./monitorLedger";
import _ from 'lodash';

export default {
    mixins: [mixin],
    components: {
        LargeTransaction,
        DubiousTransaction,
        MonitorLedger,
    },
    props: {
        date: {
            type: String,
            default: ''
        },
        type: {
            type: String,
            default: 'add'
        },
        handlePageType: {
            type: Function,
            default: () => { }
        },
        selectObj: {
            type: Object,
            default: () => { }
        },
        headId: {
            type: String,
            default: ''
        },
        reqOrgNo: {
            type: String,
            default: null,
        },
    },
    data() {
        return {
            remark: "",
            operationList: [],
            // 分页
            tablePage: {
                pageNo: 1,
                pageSize: 5,
                total: 0,
            },
            maxValue: 2147483647, // 检验输入的最大值
        }
    },
    computed: {
        ...mapState({
            language: (state) => state.base.language,
            userInfo: (state) => state.base.userInfo,
        }),
    },
    created() {
        this.getOperationData()
    },
    methods: {
        goBack() {
            this.handlePageType("home");
        },
        getOperationData() {
            // 查询操作日志只在edit || view
            if (this.type !== 'add') {
                const params = {
                    optCode: 'STM002GET1813',
                    payload: {
                        headId: this.headId,
                        rptOrgNo: this.reqOrgNo,
                        rptpd: this.date,
                    },
                    pageInfo: {
                        pageNo: this.tablePage.pageNo,
                        pageSize: this.tablePage.pageSize
                    }
                }
                this.$p2svr(
                    this.$api["_01_TSTM02MONRPT1800"],
                    "RequestPoAuth",
                    params
                ).then((res) => {
                    console.log(res, "打印操作日志的结果");
                    this.operationList = res.payload
                    this.tablePage.total = res.pageInfo ? res.pageInfo.total : 0
                    this.tablePage.pageNo = res.pageInfo ? res.pageInfo.pageNo : 1
                    this.tablePage.pageSize = res.pageInfo ? res.pageInfo.pageSize : 5
                });
            }
        },
        handleSizeChange: _.debounce(function(val) {
            const self = this
            self.tablePage.pageSize = val
            return self.getOperationData()
        }, 300),
        handleCurrentChange: _.debounce(function(val) {
            const self = this
            self.tablePage.pageNo = val
            return self.getOperationData()
        }, 300),
        filterObjects(arr) {
            return arr.filter(obj => {
                // 遍历对象的所有自身属性
                for (let key in obj) {

                    if (obj.hasOwnProperty(key)) {
                        // 跳过 sn 字段
                        if (key === 'sn') continue;

                        const value = obj[key];
                        // 检查值是否非空（非 null, undefined, 空字符串）
                        if (value !== null && value !== undefined && value !== '') {
                            return true; // 只要有一个有效值，保留对象
                        }
                    }
                }
                // 所有非 sn 字段都为空或 null，过滤掉这个对象
                return false;
            });

        },
        onAdd() {
            // 校验
            const validateArr = ['largeTransaction', 'dubiousTransaction']
            const flagArr = validateArr.map(val => this.$refs[val].validateForm())
            if (flagArr.includes(false)) {
                return
            }
            //const largeTransactionData = this.$refs.largeTransaction && this.$refs.largeTransaction?.formObj?.list;
            const largeTransactionData = this.$refs.largeTransaction && this.$refs.largeTransaction?.formObj?.cloneList;
            //console.log(largeTransactionData,"提交largeTransactionData")
            //console.log(largeTransactionData2,"largeTransactionData2-cloneList")
            const dubiousTransactionData = this.$refs.dubiousTransaction && this.$refs.dubiousTransaction?.formObj?.list;
            const monitorLedgerData = this.$refs.monitorLedger && this.$refs.monitorLedger?.list;
            const params = {
                // 有id是修改没有是新增
                optCode: "STM002MOD1814",
                payload: {
                    rptOrgNo: this.userInfo.userAhrOrg,
                    rptpd: this.date,
                    optType: this.type === "add" ? 1 : 2,
                    bgamtSpclTxnRptList: largeTransactionData ? this.filterObjects(largeTransactionData.map((item, index) => ({ sn: index + 1, ...item }))) : [],
                    sspcsTxnRptList: dubiousTransactionData ? this.filterObjects(dubiousTransactionData.map((item, index) => ({ sn: index + 1, ...item }))) : [],
                    modlStdgbList: monitorLedgerData ? this.filterObjects(monitorLedgerData.map((item, index) => ({
                        sn: index + 1,
                        ...item,
                        lstmHiDt: item.lstmHiDt ? moment(item.lstmHiDt).format('YYYY-MM-DD') : '',
                        lstmMdfDt: item.lstmMdfDt ? moment(item.lstmMdfDt).format('YYYY-MM-DD') : '',
                    }))) : [],
                },
            };

            if (this.type === 'edit') {
                if (!this.remark) {
                    this.$message.error(this.$t('stm.branchTransReportOrg.inputModReason'));
                    return
                }
            }
            params.payload.remark = this.type === 'edit' ? this.remark : this.$t('stm.common.add')
            this.$p2svr(
                this.$api["_01_TSTM02MONRPT1800"],
                "RequestPoAuth",
                params
            ).then((res) => {
                console.log(res, "打印提交的结果");
                if (res.errCode !== 'error') {
                    this.$message.success(this.type === "add" ? this.$t('stm.common.addSuccess') : this.$t('stm.common.editSuccess'));
                    this.handlePageType("home");
                }
            });
        },
    }
}
</script>

<style scoped lang="less">
.container {
    background-size: 100% 100%;

    .title {
        font-size: 26px;
        color: rgba(0, 0, 0, 0.85);
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 6px;

        &::before {
            content: "";
            width: 4px;
            height: 24px;
            background: #d21f3e;
            flex-shrink: 0; // 防止被压缩
        }
    }
}
</style>